package com.czmh.etc.onlinepubsys.utils.mingchuang;

import com.alibaba.fastjson.JSON;
import com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult;
import com.czmh.etc.onlinepubsys.json.mingchuang.UnionPayJSONResult;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.InputStream;

@Component
@Slf4j
public class HttpUtil {

    public static String url;
    public static String uploadUrl;
    public static String accessKey;
    public static String signature;
    public static String unionPayUrl;


    @Value("${mingchuang.url}")
    private String url0;
    @Value("${mingchuang.uploadUrl}")
    private String uploadUrl0;;
    @Value("${mingchuang.accessKey}")
    private String accessKey0;
    @Value("${mingchuang.signature}")
    private String signature0;
    @Value("${mingchuang.unionPayUrl}")
    private String unionPayUrl0;

    @PostConstruct
    public void init() {
        url = url0;
        uploadUrl = uploadUrl0;
        accessKey = accessKey0;
        signature = signature0;
        unionPayUrl = unionPayUrl0;
    }

    public static String postWX(String url, String xml) {
        log.info("微信支付:{}", xml);
        String res = null;
        try {
            // 响应模型
            @Cleanup
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();

            // 创建Post请求
            HttpPost httpPost = new HttpPost(url);

            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");

            StringEntity entity = new StringEntity(xml, "UTF-8");
            httpPost.setEntity(entity);

            // 由客户端执行(发送)Post请求
            @Cleanup
            CloseableHttpResponse response = httpClient.execute(httpPost);

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            if (responseEntity != null && response.getStatusLine().getStatusCode() == 200) {
                byte[] bs = EntityUtils.toString(responseEntity).getBytes("ISO8859-1");
                res = new String(bs, "UTF-8");
            }
            return res;
        } catch (Exception e) {
            log.error("微信支付请求失败", e);
            throw new RuntimeException(e);
        }
    }

    public static JSONResult post(String businessType, Object reqData) {
        String params = JSON.toJSONString(reqData);
        log.info("铭创业务号:{}, 参数:{}", businessType, params);
        JSONResult result = null;
        try {
            // 响应模型
            @Cleanup
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            StringBuilder sb = new StringBuilder(200);
            sb.append("businessType=").append(businessType).append("&accessKey=").append(accessKey)
                    .append("&signature=").append(signature).append("&reqData=").append(params);

            // 创建Post请求
            HttpPost httpPost = new HttpPost(url);

            StringEntity entity = new StringEntity(sb.toString(),
                    ContentType.create("application/x-www-form-urlencoded", "UTF-8"));
            httpPost.setEntity(entity);

            /*RequestConfig config =  RequestConfig.custom().setSocketTimeout(6000)
                    .setConnectTimeout(6000).build();
            httpPost.setConfig(config);*/

            // 由客户端执行(发送)Post请求
            @Cleanup
            CloseableHttpResponse response = httpClient.execute(httpPost);

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            if (responseEntity != null && response.getStatusLine().getStatusCode() == 200) {
                String text = EntityUtils.toString(responseEntity);
                log.info("铭创业务号:{},响应:{}", businessType, text);
                result = JSON.parseObject(text, JSONResult.class);
            }
            return result;
        } catch (Exception e) {
            log.error("铭创请求失败", e);
            throw new RuntimeException(e);
        }
    }

    public static UnionPayJSONResult postUnionPay(String method, Object reqData) {
        String params = JSON.toJSONString(reqData);
        log.info("铭创银联业务方法:{}, 参数:{}", method, params);
        UnionPayJSONResult result = null;
        try {
            // 响应模型
            @Cleanup
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            StringBuilder sb = new StringBuilder(200);
            sb.append(params);

            // 创建Post请求
            HttpPost httpPost = new HttpPost(unionPayUrl + method);

            StringEntity entity = new StringEntity(sb.toString(),
                    ContentType.create("application/json", "UTF-8"));
            httpPost.setEntity(entity);

            /*RequestConfig config =  RequestConfig.custom().setSocketTimeout(6000)
                    .setConnectTimeout(6000).build();
            httpPost.setConfig(config);*/

            // 由客户端执行(发送)Post请求
            @Cleanup
            CloseableHttpResponse response = httpClient.execute(httpPost);

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            if (responseEntity != null && response.getStatusLine().getStatusCode() == 200) {
                String text = EntityUtils.toString(responseEntity);
                log.info("铭创银联业务方法:{},响应:{}", method, text);
                result = JSON.parseObject(text, UnionPayJSONResult.class);
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("铭创银联请求失败,业务方法:{},异常信息:{}", method, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static JSONResult upload(String imageName, InputStream image) {
        log.info("铭创图片上传-开始");
        JSONResult result = null;
        try {
            // 响应模型
            @Cleanup
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            StringBuilder sb = new StringBuilder(uploadUrl);
            sb.append("?accessKey=").append(accessKey).append("&signature=").append(signature);
            // 创建Post请求
            HttpPost httpPost = new HttpPost(sb.toString());

            log.info("铭创图片上传-url：" + sb.toString());
            HttpEntity entity = MultipartEntityBuilder.create()
                    .addPart("imageName", new StringBody(imageName,
                            ContentType.create("multipart/form-data", Consts.UTF_8)))
                    .addPart("image", new InputStreamBody(image, imageName))
                    .build();

            httpPost.setEntity(entity);

            /*RequestConfig config = RequestConfig.custom().setSocketTimeout(6000)
                    .setConnectTimeout(6000).build();
            httpPost.setConfig(config);*/

            // 由客户端执行(发送)Post请求
            @Cleanup
            CloseableHttpResponse response = httpClient.execute(httpPost);

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            log.info("铭创图片上传-返回结果：" + JSON.toJSONString(response));
            if (responseEntity != null && response.getStatusLine().getStatusCode() == 200) {
                result = JSON.parseObject(EntityUtils.toString(responseEntity), JSONResult.class);
            }
            return result;
        } catch (Exception e) {
            log.error("铭创图片上传失败", e);
            throw new RuntimeException(e);
        }
    }
}
